import { createRouter, createWebHistory } from 'vue-router';
import { ElMessage } from "element-plus";
import ShopView from '@/views/ShopView.vue';
import OrderView from '@/views/OrderView.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { 
      path: '/', 
      redirect: '/login' 
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/LoginView.vue'),
      meta:{
        title:'登录'
      }
    },
    {
      path: '/admin',
      name: 'admin',
      hidden: true,
      redirect: { name: 'goods' },
      component: () => import('../views/AdminView.vue'),
      children: [
        {
          path: 'goods',
          name: 'goods',
          label: '商品管理',
          hidden: false,
          icon: 'Goods',
          component: () => import('../views/GoodsView.vue')
        },
        {
          path: 'user',
          name: 'user',
          label: '用户管理',
          hidden: false,
          icon: 'User',
          component: () => import('@/views/UserView.vue'),
        },
        {
          path: 'comment',
          name: 'comment',
          label: '评论管理',
          hidden: false,
          icon: 'ChatLineRound',
          component: () => import('../views/CommentManage.vue')
        },
        {
          path: 'order',
          name: 'order',
          label: '订单管理',
          hidden: false,
          icon: 'ShoppingCartFull',
          component: OrderView
        },
        {
          path: 'data',
          name: 'data',
          label: '数据分析',
          hidden: false,
          icon: 'DataLine',
          component: () => import('../views/DataView.vue')
        },
        {
          path: 'promotion',
          name: 'promotion',
          label: '促销活动管理',
          hidden: false,
          icon: 'ShoppingCartFull',
          component: () => import('../views/Promotion.vue')
        }
      ]
    },
    {
      path: '/404',
      name: '404',
      component: () => import('../views/404.vue')
    }
  ]
})

//全局前置路由守卫
let whiteList=['/','/login','/401'];
let routerList=[
  '/',
  '/login',
  '/admin/shop',
  '/admin/goods',
  '/admin/user',
  '/admin/comment',
  '/admin/order',
  '/admin/data',
  '/admin/user-profile',
  '/admin/promotion',
  '/404'
]
router.beforeEach((to, from, next) => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  if (userInfo && userInfo.role === 'admin') { // 已登录且是管理员
    if (to.path === '/login') {
      // 已登录不能再访问登录页，跳转到首页
      next({ path: '/admin/data' });
    } else if (routerList.indexOf(to.path) > -1) {
      next();
    } else {
      next({ path: '/404' });
    }
  } else { // 未登录或不是管理员
    if (to.path === '/login') {
      next();
    } else {
      ElMessage.error("请先登录");
      next({ path: '/login' });
    }
  }
})

export default router
